package com.rchat.pocmini.activity.chatmessage;

import android.content.Context;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.ListView;

import com.airtalkee.sdk.entity.AirMessage;
import com.hyphenate.easeui.widget.emojicon.EaseChatExtendMenu;
import com.hyphenate.easeui.widget.emojicon.EaseChatInputMenu;
import com.hyphenate.easeui.widget.emojicon.utils.EaseEmojicon;
import com.rchat.pocmini.R;
import com.rchat.pocmini.activity.fragment.groups.GroupsPresenterImpl;
import com.rchat.pocmini.activity.view.MessageRecordingView;
import com.rchat.pocmini.activity.view.chat.CustomTitleBar;
import com.rchat.pocmini.common.mvp.BaseMvpActivity;
import com.rchat.pocmini.message.PocAirtalkeeMessage;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

/**
 * Created by ljd on 2017/9/28.
 *
 */

public class ChatMessageMvpActivity  extends BaseMvpActivity<ChatMessagePresenterImpl, ChatMessageModelImpl> implements
        ChatMessageContract.View,
        ChatMessageAdapter.OnMessageItemClickedListener{


    @BindView(R.id.lv_chat_list)
    ListView lvMessage;

    @BindView(R.id.input_menu)
    EaseChatInputMenu inputMenu;


    @BindView(R.id.customtitlebar)
    CustomTitleBar customtitlebar;

    @BindView(R.id.mrv_talking_recording)
    MessageRecordingView vRecording;


    private String groupId;
    private String groupName;
    static final int ITEM_TAKE_PICTURE = 1;
    static final int ITEM_PICTURE = 2;
    static final int ITEM_LOCATION = 3;
    protected int[] itemStrings = {R.string.attach_picture};
    protected int[] itemDrawables = {R.drawable.icon_chat_takepic};
    protected int[] itemIds = {ITEM_PICTURE};

    private ExtendItemClickListener extendMenuItemClickListener;
    private InputMethodManager mInputMethodManager;

    private List<AirMessage> messageList = new ArrayList<>();
    private ChatMessageAdapter adapter;


    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
        groupId = getIntent().getStringExtra(GroupsPresenterImpl.KEY_GROUPID);
        groupName = getIntent().getStringExtra("groupName");
    }

    @Override
    public int getLayoutId() {
        return R.layout.chat_message_activity_layout;
    }

    @Override
    public void initView() {
        mInputMethodManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        extendMenuItemClickListener = new ExtendItemClickListener();

        customtitlebar.setActivity(this);
        customtitlebar.setCenterTitle(groupName);

        vRecording.initChild();


        inputMenu.init(null);
        inputMenu.setChatInputMenuListener(new EaseChatInputMenu.ChatInputMenuListener() {
            @Override
            public void onSendMessage(String content) {
                //按了发送按钮
                mPresenter.messageSend(groupId,content);
            }

            @Override
            public void onBigExpressionClicked(EaseEmojicon emojicon) {

            }

            @Override
            public boolean onPressToSpeakBtnTouch(View v, MotionEvent event) {
                //按住讲话
                mPresenter.speakBtnTouch(groupId,v,event);
                return false;
            }
        });


        adapter = new ChatMessageAdapter(this, messageList,this);
        lvMessage.setAdapter(adapter);
        mPresenter.loadFirstPageData(groupId);

        lvMessage.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideKeyboard();
                inputMenu.onBackPressed();
                return false;
            }
        });
        lvMessage.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                mPresenter.messageListScroll(groupId,view,scrollState);
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                // TODO Auto-generated method stub

            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void doAfterInitView() {

    }

    @Override
    public void showMessage(List<AirMessage> list) {
        messageList.addAll(list);
        sequencList(messageList);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void setMessageListSelection(int Selection, boolean selected) {
        lvMessage.setSelection(Selection);
        lvMessage.setSelected(selected);
    }

    @Override
    public void showMessage(AirMessage airMessage) {
        messageList.add(airMessage);
        sequencList(messageList);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void showRecordingView(int paramInt, Object paramObject) {
        vRecording.registerMessage(paramInt, paramObject);
    }

    @Override
    public void removeMessage() {
        int len = messageList.size();
        if (messageList.get(len - 1).getState() == AirMessage.STATE_GENERATING) {
            messageList.remove(len - 1);
            adapter.notifyDataSetChanged();
            lvMessage.setSelection(len - 2);
        }
    }

    @Override
    public void setRecordPlaying(AirMessage currentAirMsg) {
        int len = messageList.size();
        for (int i = 0; i < len; i++) {
            if (messageList.get(i).getMessageCode().equals(currentAirMsg.getMessageCode())) {
                messageList.get(i).setRecordPlaying(currentAirMsg.isRecordPlaying());
                adapter.notifyDataSetChanged();
                break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        //用户点击了消息，如果是录音，就要执行播放录音
        mPresenter.soundMessagePlay(v);
    }


    /**
     * handle the click event for extend menu
     */
    private class ExtendItemClickListener implements EaseChatExtendMenu.EaseChatExtendMenuItemClickListener {

        @Override
        public void onClick(int itemId, View view) {
            switch (itemId) {
                case ITEM_TAKE_PICTURE:
                    break;
                case ITEM_PICTURE:
//                    pickPicture();
                    break;
                case ITEM_LOCATION:
                    break;

                default:
                    break;
            }
        }

    }

    /**
     * hide
     */
    protected void hideKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                mInputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    protected void registerExtendMenuItem() {
        for (int i = 0; i < itemStrings.length; i++) {
            inputMenu.registerExtendMenuItem(itemStrings[i], itemDrawables[i], itemIds[i], extendMenuItemClickListener);
        }
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (inputMenu.onBackPressed()) {
            mPresenter.backPressed(inputMenu.getPrimaryMenu().getEditText().getText().toString());

        }
    }

    @Override
    public void backPressed(AirMessage currentAirMsg,PocAirtalkeeMessage pocAirtalkeeMessage) {
        if (currentAirMsg != null && currentAirMsg.isRecordPlaying()) {
            int pos = messageList.indexOf(currentAirMsg);
            messageList.get(pos).setRecordPlaying(true);
            adapter.notifyDataSetChanged();
            pocAirtalkeeMessage.messageRecordPlayStop();
        }
        doGoBack();
    }

    /**
     * 根据时间排序
     * @param list
     */
    private void sequencList(List<AirMessage> list) {
        Collections.sort(list, new Comparator<AirMessage>() {
            @Override
            public int compare(AirMessage o1, AirMessage o2) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
                try {
                    Date dt1 = format.parse(o1.getDate() + o1.getTime());
                    Date dt2 = format.parse(o2.getDate() + o2.getTime());
                    if (dt1.getTime() > dt2.getTime()) {
                        return 1;
                    } else if (dt1.getTime() < dt2.getTime()) {
                        return -1;
                    } else {
                        return 0;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });
    }
}
